import http from '@ohos.net.http'
import PhotosBean from '../bean/PhotosBean';
import PostaBean from '../bean/PostaBean'


class PostsModel {
  baseUrl: string = "http://jsonplaceholder.typicode.com/"


  // @ts-ignore
  getPostsList(): Promise<PostaBean[]> {
    return new Promise((resolve, reject) => {
      var httpRequest = http.createHttp();
      httpRequest.request(this.baseUrl + "posts?_page=1&_limit=10",
        {
          method: http.RequestMethod.GET,
          header: {},
          connectTimeout: 10000, //设置超时时间
          readTimeout: 10000, //设置读取时间
          extraData: { '_page': 1, "_limit": 10 },
        },
      )
        //处理响应结果 Promise存放未来会完成的结果
        .then((resp: http.HttpResponse) => {
          console.log("http", "=====网络请求数据=======" + JSON.stringify(resp))
          if (resp.responseCode === 200) {
            //请求成功
            resolve(JSON.parse(resp.result.toString()))
          } else {
            reject("网络请求失败！")
          }
        }).catch((err: Error) => {
        //请求失败
        reject("网络请求失败！")
        console.log("http", JSON.stringify(err))
      })
    });
  }

  //获取照片列表
  // photos
  getPhotosList(page:number): Promise<PhotosBean[]> {
    return new Promise((resolve, reject) => {
      var httpRequest = http.createHttp();
      httpRequest.request(this.baseUrl + "photos?_page="+page+"&_limit=10",
        {
          method: http.RequestMethod.GET,
          header: {},
          connectTimeout: 10000,
          readTimeout: 10000,
          extraData: {}
        }
      ).then((resp: http.HttpResponse) => {
        if (resp.responseCode === 200) {
          resolve(JSON.parse(resp.result.toString()))
        } else {
          reject("网络请求失败！")
        }
      }).catch((err: Error) => {
        reject("网络请求失败！")
        console.log("http", JSON.stringify(err))
      })
    })
  }

  //获取照片详情
  getPhotoDetails(id:string): Promise<PhotosBean> {
    return new Promise((resolve, reject) => {
      var httpRequest = http.createHttp();
      httpRequest.request(this.baseUrl + "photos/"+id,
        {
          method: http.RequestMethod.GET,
          header: {},
          connectTimeout: 10000, //设置超时时间
          readTimeout: 10000, //设置读取时间
          extraData: { '_page': 1, "_limit": 10 },
        },
      )
        //处理响应结果 Promise存放未来会完成的结果
        .then((resp: http.HttpResponse) => {
          console.log("http", "=====网络请求数据=======" + JSON.stringify(resp))
          if (resp.responseCode === 200) {
            //请求成功
            resolve(JSON.parse(resp.result.toString()))
          } else {
            reject("网络请求失败！")
          }
        }).catch((err: Error) => {
        //请求失败
        reject("网络请求失败！")
        console.log("http", JSON.stringify(err))
      })
    });
  }
}

const postsModel = new PostsModel()

export default postsModel as PostsModel
